import fs from 'fs'
import path from 'path'
import Oss, { NodeFile } from '@/tools/rawa-oss'
import { upload as uploadFile } from '@/api/doc'

const uid = 1100000

function genUuid (): string {
  return Date.now() + '-' + uid + '-' + String(Math.random()).slice(-4)
}

export function uploadFromLocal (localPath: string, name: string, parentDocId: number): Promise<any> {
  const client = new Oss({
    endpoint: '',
    accessKeyId: '',
    accessKeySecret: '',
    stsToken: '',
    bucket: 'fs'
  })
  const p = `${genUuid()}/` + name
  return getFile(localPath, name).then(data => {
    return client.multipartUpload(p, data).then(res => ({ f: data, res }))
  }).then(({ f, res }) => {
    const req = {
      parentId: parentDocId,
      name,
      size: f.size,
      url: (res.res as any)?.requestUrls[0]
    }
    return uploadFile(req)
  })
}

function getFile (p: string, name: string): Promise<File | NodeFile> {
  return new Promise((resolve, reject) => {
    fs.stat(p, (err, stats) => {
      if (err) {
        reject(err)
        return
      }
      if (stats.size > 1024 * 1024 * 1) {
        resolve(new NodeFile(p, stats.size))
      } else {
        fs.readFile(p, (err, data) => {
          if (err) reject(err)
          else {
            const file = new File([data as any], name)
            return resolve(file)
          }
        })
      }
    })
  })
}
